package fwx.servlet;

import fwx.dao.UserDao;
import fwx.dao.impl.UserDaoImpl;
import fwx.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        //查询用户名是否存在于数据库，如果存在用户就不写入数据库
        UserDao userDao = new UserDaoImpl();
        User user1 = userDao.findUserByName(userName);
        if(user1 == null) {
            //插入数据库
            System.out.println("执行2");
            User user2 = new User(userName,password);
            //默认普通用户
            user2.setAdmin(0);
            userDao.addUser(user2);
            //跳转到登录页面
            request.getRequestDispatcher("/login.html").forward(request,response);
        }else {
            //存在此用户，重新注册
            request.getRequestDispatcher("/register.html").forward(request,response);
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
